import hashlib
import json
from account.account_service import AccountService, accounts_write_lock
from common.logger import logger
import common.http as http


class EParkAccountService(AccountService):
    
    def __init__(self):
        super().__init__()
        
        self.openids = [
            ("oEe3kwQHonscWpbwgnDCRmoCh_G8", "0be71edeb0e6b5f74d28329d1f4c3c7c")
        ]
    
    def active(self):
        pass
    
    def fetch(self):
        for openid, sign in self.openids:
            account = self.getAccountByOpenId(openid, sign)
            if account:
                self.add(account)
                logger.success(f"添加账号 {account['mobile']} 成功")
            else:
                logger.error(f"添加账号 {account['mobile']} 失败")
    
    def getAccountByOpenId(self, openid, sign):
        
        data = json.dumps(
            {"openid": openid},
            ensure_ascii=False,
            separators=(",", ":"),
        )

        #sign = hashlib.md5(data.encode("utf-8")).hexdigest()

        params = {
            "token": "",
            "ver": "3",
            "client": "3",
            "sign": sign,
            "ua": openid[0:-1],
            "cid": "1",
        }

        url = 'https://mp.ebopark.com/lpn/user/GetInfoByOpenId'

        headers = {
            "Host": "mp.ebopark.com",
            "Content-Type": "application/json",
            "User-Agent": "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat(0x63090621) XWEB/8259 Flue",
        }

        rsp = http.post(
            url,
            params=params,
            headers=headers,
            data=data.encode("utf-8"),
        )

        rspJson = rsp.json()
        
        if rspJson["state"] == 0:
            return rspJson["result"]

        return None

    def take(self):
        with accounts_write_lock:
            if not self._accounts:
                self.fetch()
            return super().take()